var crypto = require('crypto');
var User = require('../models/user');

module.exports = function(app){
	app.get('/', function(req, res){

		res.render('index', { title: 'Express'});
	});

	app.get('/reg', function(req, res){
		res.render('reg', {title:'注册', userName :''});
	});

	app.post('/reg', function(req, res){
		console.log('--->password:' + req.body['password'] + " " + req.body['repeat-password']);
		if(req.body['password'] != req.body['repeat-password']){
			req.flash('error', '两次输入的密码不一致');
			console.log('--->两次输入的密码不一致');
			return res.redirect('/reg');
		} else {
			var md5 = crypto.createHash('md5');
			console.log('--->md5:' + md5);
			var password = md5.update(req.body.password).digest('base64');
			console.log("---->password:" + password);

			var newUser = new User({
				name:req.body.userName,
				password:password
			});

			User.get(newUser.name, function(err, user){
				console.log('进入get方法');
				if(user){
					err = 'userName already exists';
					console.log('用户已经存在');
				}

				if(err){
					req.flash('error', err);
					console.log('重定向到/reg');
					return res.redirect('/reg');
				}

				newUser.save(function(err){
					console.log('保存用户信息');
					if(err){
						req.flash('error', err);
						console.log('保存失败:' + error);
						res.redirect('/reg');
					}

					console.log('保存用户信息成功');
					req.session.user = newUser;
					req.flash('success', '注册成功');
					res.redirect('/');
				});
			});
		}
	});
};